<!-- 施工明细 -->
<template>
  <div>
    <el-form class="searchForm">
      <el-form-item style="margin-left: 10px;">
        <!-- <el-input v-model="params.date" placeholder="项目名" style="width: 120px;"  clearable></el-input> -->
        <el-select placeholder="项目名" v-model="params.contractId" clearable>
          <el-option v-for="c of contract" :label="c.projectName" :value="c.contractId" :key="c.contractId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="本期结算周期：" style="margin-left: 10px;">
        <el-date-picker v-model="params.date" type="daterange" unlink-panels range-separator="To" start-placeholder="开始日期"
          end-placeholder="结束日期" size="large" />
      </el-form-item>
      <el-form-item style="margin-left: 10px;">
        <el-button type="primary" @click="getCommodityPageList">
          <el-icon>
            <svg t="1646977561352" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="3057" width="200" height="200">
              <path
                d="M986.304 871.424L747.328 630.4c-2.816-2.752-5.888-4.928-8.768-7.232 40.32-62.464 63.936-136.832 63.936-216.96 0-220.16-176.96-398.592-395.392-398.592C188.8 7.616 11.712 186.048 11.712 406.208s177.088 398.592 395.392 398.592a391.232 391.232 0 0 0 215.36-64.576c2.24 3.072 4.352 6.08 7.04 8.832l239.04 241.024a82.688 82.688 0 0 0 117.76 0 84.48 84.48 0 0 0 0-118.656m-579.2-192.512c-149.12 0-270.528-122.368-270.528-272.704 0-150.4 121.344-272.768 270.528-272.768 149.12 0 270.528 122.432 270.528 272.768 0 150.4-121.408 272.704-270.528 272.704"
                p-id="3058"></path>
            </svg>
          </el-icon>
          &nbsp;查&nbsp;&nbsp;询
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <!-- 表格 -->
  <el-table ref="multipleTableRef" :data="commodityPageList" @selection-change="handleSelectionChange"
    style="width: 100%; margin-top: 10px;" table-layout="auto" size="large" border id="elTable" :span-method="arraySpanMethod">
    <!-- :summary-method="getSummaries" show-summary -->
    <el-table-column type="selection" width="55" />
    <el-table-column prop="category" label="类别" sortable />
    <el-table-column prop="type" label="项目名称" sortable />
    <el-table-column prop="unitName" label="单位" sortable />
    <el-table-column prop="unitPrice" label="单价" sortable />
    <el-table-column label="合同清单" sortable>
      <el-table-column prop="number" label="数量" sortable />
      <el-table-column prop="money" label="金额" sortable />
    </el-table-column>
    <el-table-column label="至上期未完成" sortable>
      <el-table-column prop="oldNumber" label="数量" sortable />
      <el-table-column prop="oldMoney" label="金额" sortable />
    </el-table-column>
    <el-table-column label="本期完成" sortable>
      <el-table-column prop="newNumber" label="数量" sortable />
      <el-table-column prop="newMoney" label="金额" sortable />
    </el-table-column>
    <el-table-column label="至本期末累计完成" sortable>
      <el-table-column prop="endNumber" label="数量" sortable />
      <el-table-column prop="endMoney" label="金额" sortable />
      <el-table-column label="比例" sortable :formatter="proportion" />
    </el-table-column>
    <el-table-column prop="constructionDetails.remark" label="备注" sortable />
  </el-table>
  <!-- 分页 -->
  <!-- <el-pagination background :total="params.totalNum" :page-sizes="[5, 10, 15, 20, 25, 30]"
    v-model:page-size="params.pageSize" v-model:currentPage="params.pageNum"
    layout="total, sizes, prev, pager, next, jumper" style="margin-top: 20px;" @size-change="changeSize"
    @current-change="changeCurrent" /> -->

  <!-- 添加类型对话框 -->
  <commodity-add ref="commodityAddRef" @ok="getCommodityPageList"></commodity-add>

  <!-- 修改类型对话框 -->
  <commodity-update ref="commodityUpdateRef" @ok="getCommodityPageList"></commodity-update>
</template>
<script setup>
import { reactive, ref, h } from 'vue';
import { get, put, del, tip, export2excel, WAREHOUSE_CONTEXT_PATH, post, eltable2excel } from "@/common";
import { useRoute, useRouter } from "vue-router";
import { Search, Edit, Check, Message, Star, Delete } from '@element-plus/icons-vue'

const router = useRouter(); // 获取路由器

// 分页模糊查询数据
const params = reactive({
  contractId: '',
  date: []
})

// 表格数据
const commodityPageList = ref();

const isPurchase = ref(false);

// 获取路由信息
const route = useRoute();
// 获取分页模糊查询结果
const newParams = ref();
const getCommodityPageList = () => {
  if (params.date.length != 0) {
    newParams.startTime = formatDate(params.date[0])
    newParams.endTime = formatDate(params.date[1])
  }
  newParams.contractId = params.contractId
  post("/construction/collectSettleAccounts", newParams).then(result => {
    commodityPageList.value = result.data;
  });
}
// getCommodityPageList();

// 日期格式化函数
function formatDate(dateStr) {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 所有产品
const productList = ref();
// 获取所有产品
const getStoreList = () => {
  get("/product/product-list").then(result => {
    productList.value = result.data;
  });
}
getStoreList();

// 所有单位
const unitList = ref();
// 获取所有单位
const getUnitList = () => {
  get("/material/unit-list").then(result => {
    unitList.value = result.data;
  });
}
getUnitList();

// 施工类型
const type = ref();
const getAllType = () => {
  get("/constructionType/constructionType-list").then(result => {
    type.value = result.data;
  })
}
getAllType();

// 复选框的操作
const multipleTableRef = ref();
const multipleSelection = ref([]);
// const toggleSelection = (rows) => {
//   if (rows) {
//     rows.forEach((row) => {
//       multipleTableRef.value.toggleRowSelection(row, undefined)
//     })
//   } else {
//     multipleTableRef.value.clearSelection()
//   }
// }
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
}

// 导出数据
const export2Table = () => {
  eltable2excel("elTable")
}

const check = () => {
  return row.constructionType.measurement
}


// 跳向添加类型
import CommodityAdd from "./constructionDetails-add.vue";
const commodityAddRef = ref();
const openCommodityAdd = () => {
  commodityAddRef.value.open(productList, unitList, type);
};


// 跳向修改类型
import CommodityUpdate from "./constructionDetails-update.vue";
const commodityUpdateRef = ref();
const openCommodityUpdate = (commodity) => {
  commodityUpdateRef.value.open(commodity, productList, unitList, type);
};

// 删除单个类型
const deleteCommodity = (id) => {
  del(`/construction/delete/${id}`, null, { title: "提示", message: "您确定删除该明细吗？" }).then(result => {
    tip.success(result.message);
    // 重新查询
    getCommodityPageList();
  });
}

const contract = ref();
const getContract = () => {
  get("/contract/contract-all").then(result => {
    contract.value = result.data;
  })
}
getContract();

const location = ref();
// 获得所有位置
const getLocation = (i) => {
  if (i == 1) {
    get("/location/location-list").then(result => {
      location.value = result.data;
    })
  } else {
    get("/location/location-list/" + params.contractId).then(result => {
      location.value = result.data;
    })
  }
};
getLocation(1);

// 选择项目
const changeContract = () => {
  console.log("changeContract")
  getLocation(2);
}


// 修改每页显示条数
const changeSize = (size) => {
  params.pageSize = size;
  // 重新查询
  getCommodityPageList();
}
// 修改当前页码
const changeCurrent = (num) => {
  params.pageNum = num;
  // 重新查询
  getCommodityPageList();
}

const constructionNumber1 = (row) => {
  return row.constructionType.measurement == '施工长度' ? row.constructionDetails.number : null;
}
const constructionNumber2 = (row) => {
  return row.constructionType.measurement == '施工数量' ? row.constructionDetails.number : null;
}

const proportion = (row) => {
  if(row.type === "合计"){
    return ''
  }
  return row.proportion * 100 + '%'
}

// 合计
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = ref([]);
  columns.forEach((column, index) => {
    if (index === 2) {
      sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
        '合计',
      ])
      return
    }
    if (index == 4 || index == 5) {
      const values = data.map((item) => Number(item[column.property]))
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        }, 0)}`
      } else {
        sums[index] = ''
      }
    }
  })
  return sums
}

const arraySpanMethod = (rows) => {
  let row = rows.row
  let column = rows.column
  let rowIndex = rows.rowIndex
  let columnIndex = rows.columnIndex
  // 行
  if (row.type === "合计") {
    if (columnIndex === 2) {
      return [1, 3]
    } else if (columnIndex < 5 && columnIndex > 2) {
      return [0, 0]
    }
  }

  // 列
  if (columnIndex === 1) {
    if (row.category === "计量") {
      if(rowIndex === 0){
        // console.log(rowIndex + "," + columnIndex)
        // console.log(row)
      // console.log(commodityPageList.value.length)
      return [3, 1]
      }else {
      return [0,0]
    }
    }
  }

}

</script>
  
<style scoped>
.searchForm {
  margin-top: 20px;
  display: flex;
}

.el-link {
  margin-right: 8px;
}
</style>